using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;
using System.Collections.Generic;
//用于管理鼠标上的物品数据
public class MouseItemData : MonoBehaviour
{
    public Image ItemSprite; // 物品图像的引用
    public TextMeshProUGUI ItemCount; // 物品数量的引用

    public InventorySlot AssignedInventorySlot; // 当前鼠标槽所关联的物品槽

    private void Awake()
    {
        ItemSprite.color = Color.clear; // 设置物品图像的颜色为透明
        ItemSprite.preserveAspect = true;
        ItemCount.text = ""; // 清空物品数量的文本
    }

    public void UpdateMouseSlot(InventorySlot invSlot)
    {
        AssignedInventorySlot.AssignItem(invSlot); // 将传入的物品槽数据赋值给当前鼠标槽所关联的物品槽
        UpdateMouseSlot();
    }

    public void UpdateMouseSlot()
    {
        ItemSprite.sprite = AssignedInventorySlot.ItemData.Icon; // 更新鼠标槽显示的物品图标
        ItemCount.text = AssignedInventorySlot.StackSize.ToString(); // 更新鼠标槽显示的物品堆叠数量文本
        ItemSprite.color = Color.white; // 设置鼠标槽显示的物品图标颜色为白色
    }

    private void Update()
    {
        if (AssignedInventorySlot.ItemData != null)
        {
            transform.position = Input.mousePosition;  // 更新鼠标槽的位置

            // 检查鼠标左键是否按下并且没有点击在UI上
            if (Input.GetMouseButtonDown(0) && !IsPointerOverUIObject())
            {
                //丢弃物品
                if (AssignedInventorySlot.ItemData.ItemPrefab != null)
                {
                    Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                    Instantiate(AssignedInventorySlot.ItemData.ItemPrefab, mousePosition, Quaternion.identity);
                }
                if (AssignedInventorySlot.StackSize > 1)
                {
                    AssignedInventorySlot.AddToStack(-1); //堆叠中减少物品数量
                    UpdateMouseSlot();
                }
                else
                {
                    ClearSlot();  // 清空鼠标槽的物品数据
                }
            }
        }
    }

    // 清空鼠标槽位的方法
    public void ClearSlot()
    {
        AssignedInventorySlot.ClearSlot();  // 清空关联的物品槽数据
        ItemCount.text = "";                // 清空物品数量文本
        ItemSprite.color = Color.clear;     // 设置物品图像颜色为透明
        ItemSprite.sprite = null;           // 清空物品图像
    }

    // 检查鼠标是否在UI上的方法
    public static bool IsPointerOverUIObject()
    {
        // PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        // eventDataCurrentPosition.position = Input.mousePosition;
        // List<RaycastResult> results = new List<RaycastResult>();
        // EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        // return results.Count > 0;
        //检查鼠标当前位置是否在UI对象上
        return EventSystem.current.IsPointerOverGameObject();
    }
}